package com.example.backetballgame.gui;

import com.example.backetballgame.player.Player;
import com.example.backetballgame.store.StoreFactory;
import com.example.backetballgame.store.StoreManage;
import com.example.backetballgame.team.Team;

import javax.swing.*;
import java.awt.*;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


/**
 * The frame for selecting opponent team before the battle.
 */
public class SelectOpponentFrame extends JFrame {
    private JPanel opponentPanel;
    private JButton backButton;
    private JButton continueButton;
    private ButtonGroup teamButtonGroup;
    private JLabel rewardLabel;

    /**
     * Constructs the frame for selecting opponent team.
     * Sets up the GUI components and binds events.
     */
    public SelectOpponentFrame() {
        // Window settings
        setTitle("Select Opponent Team");
        setSize(600, 500);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        // Opponent team information in the middle
        opponentPanel = new JPanel(new GridLayout(0, 1, 10, 10));
        opponentPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JScrollPane galleryScrollPane = new JScrollPane(opponentPanel);
        galleryScrollPane.setPreferredSize(new Dimension(0, 300));

        ArrayList<Team> teamList = new ArrayList<>();
        Team team1 = new Team("Team 1", "Opponent 1", 10, 20, 10, 10);
        team1.setPlayerList(generatePlayers());
        teamList.add(team1);

        Team team2 = new Team("Team 2", "Opponent 2", 20, 30, 15, 15);
        team2.setPlayerList(generatePlayers());
        teamList.add(team2);

        Team team3 = new Team("Team 3", "Opponent 3", 30, 40, 20, 20);
        team3.setPlayerList(generatePlayers());
        teamList.add(team3);

        Team team4 = new Team("Team 4", "Opponent 4", 40, 50, 25, 25);
        team4.setPlayerList(generatePlayers());
        teamList.add(team4);

        Team team5 = new Team("Team 5", "Opponent 5", 50, 60, 30, 30);
        team5.setPlayerList(generatePlayers());
        teamList.add(team5);

        Team team6 = new Team("Team 6", "Opponent 6", 60, 70, 35, 35);
        team6.setPlayerList(generatePlayers());
        teamList.add(team6);

        teamButtonGroup = new ButtonGroup();
        for (Team team : teamList) {
            JPanel teamCard = new JPanel(new GridLayout(1, 2));
            teamCard.setBorder(BorderFactory.createLineBorder(Color.black));

            JPanel infoPanel = new JPanel(new GridLayout(5, 1, 0, 4));
            infoPanel.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));
            JLabel teamNameLabel = new JLabel(team.getTeamName());
            JLabel opponentLabel = new JLabel("Opponent: " + team.getOpponent());
            JLabel pointsLabel = new JLabel("Points: " + team.getPoints());
            JLabel matchCountLabel = new JLabel("Match Count: " + team.getMatchCount());
            JLabel recordLabel = new JLabel("Record: " + team.getWinCount() + "-" + team.getLoseCount());
            infoPanel.add(teamNameLabel);
            infoPanel.add(opponentLabel);
            infoPanel.add(pointsLabel);
            infoPanel.add(matchCountLabel);
            infoPanel.add(recordLabel);

            JRadioButton teamRadioButton = new JRadioButton();
            teamRadioButton.setActionCommand(team.getTeamName());
            teamRadioButton.setHorizontalAlignment(SwingConstants.RIGHT);
            teamButtonGroup.add(teamRadioButton);


            teamCard.add(infoPanel);
            teamCard.add(teamRadioButton);

            opponentPanel.add(teamCard);

            teamRadioButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {

                    teamList.stream().filter(it -> it.getTeamName().equals(teamRadioButton.getActionCommand()))
                            .findFirst().ifPresent(team -> {
                                // Calculate reward
                                int points = team.getPoints();
                                int gold = team.getGoldReward();
//                                int fatigue = team.getFatigueCost();

//                                rewardLabel.setText("Reward: " + points + " points, " + gold + " gold, " + fatigue + " fatigue");
                                rewardLabel.setText("Reward: " + points + " points, " + gold + " gold");
                            });
                }
            });
        }
        add(galleryScrollPane, BorderLayout.CENTER);

        // Bottom buttons and reward display
        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 0));
        JPanel buttonPanel = new JPanel(new FlowLayout());
        backButton = new JButton("Back");
        continueButton = new JButton("Continue");
        buttonPanel.add(backButton);
        buttonPanel.add(continueButton);
        bottomPanel.add(buttonPanel, BorderLayout.NORTH);
        rewardLabel = new JLabel("--------------------");
        bottomPanel.add(rewardLabel, BorderLayout.CENTER);

        add(bottomPanel, BorderLayout.SOUTH);

        // Bind button events
        backButton.addActionListener(event -> dispose());
        continueButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ButtonModel selection = teamButtonGroup.getSelection();
                if (selection == null) {
                    JOptionPane.showMessageDialog(null, "Please chose battle team!");
                    return;
                }
                String selectedTeamName = selection.getActionCommand();

                teamList.stream().filter(it -> it.getTeamName().equals(selectedTeamName)).findFirst().ifPresent(team -> {

                    // Calculate reward
                    int points = team.getPoints();
                    int gold = team.getGoldReward();
                    rewardLabel.setText("Reward: " + points + " points, " + gold + " gold");

                    // Enter the battle interface and pass the selected team name
                    dispose(); // Close the current selection of battle team interface

                    StoreManage.saveOpponentTeam(team);

                    BattleFrame matchFrame = new BattleFrame();
                    // Create the battle interface, and pass the selected team name and reward
                    matchFrame.setVisible(true); // Display the battle interface
                });
            }
        });
    }

    /**
     * Generates a list of players with random attributes.
     *
     * @return the list of players
     */
    private List<Player> generatePlayers() {
        List<Player> players = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            players.add(StoreFactory.createPlayer());
        }
        return players;
    }

    /**
     * The entry point of the program.
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SelectOpponentFrame frame = new SelectOpponentFrame();
        frame.setVisible(true);
    }
}



